from django.utils.decorators import method_decorator

from gis.admin.decorators import require_login, check_permission
from gis.common.django_ext.decorators import validate_parameters
from gis.common.django_ext.views import BaseView, PaginationResponse
from itpay.core.sys import bulletin_service, export_service
from itpay.server_admin.decorators import require_vcode
from itpay.server_admin.view.sys.helper import wrap_bulletin_info
from . import bulletin_form


class BulletinView(BaseView):
    @method_decorator(require_login)
    @method_decorator(check_permission('bulletin_get'))
    @method_decorator(validate_parameters(bulletin_form.GetBulletinSchema))
    def get(self, request, cleaned_data):
        c, ls = bulletin_service.list_bulletin(**cleaned_data, with_mch_info=True)
        return PaginationResponse(c, [wrap_bulletin_info(e) for e in ls])

    @method_decorator(require_login)
    @method_decorator(require_vcode)
    @method_decorator(check_permission('bulletin_add'))
    @method_decorator(validate_parameters(bulletin_form.AddBulletinSchema))
    def post(self, request, cleaned_data):
        return bulletin_service.add_bulletin(**cleaned_data)


class BulletinDetailView(BaseView):
    @method_decorator(require_login)
    @method_decorator(check_permission('bulletin_get'))
    def get(self, request, bulletin_id):
        bulletin = bulletin_service.get_bulletin(bulletin_id, with_mch_info=True)
        return bulletin

    @method_decorator(require_login)
    @method_decorator(require_vcode)
    @method_decorator(check_permission('bulletin_update'))
    @method_decorator(validate_parameters(bulletin_form.UpdateBulletinSchema))
    def put(self, request, bulletin_id, cleaned_data):
        bulletin_service.update_bulletin(bulletin_id, **cleaned_data)
        return dict(id=bulletin_id)

    @method_decorator(require_login)
    @method_decorator(require_vcode)
    @method_decorator(check_permission('bulletin_del'))
    def delete(self, request, bulletin_id):
        bulletin_service.delete_bulletin(bulletin_id)
        return dict(id=bulletin_id)


class ExportTaskDetailView(BaseView):
    @method_decorator(require_login)
    def get(self, request, task_id):
        task = export_service.get_task_by_id(task_id)
        return task
